package net.lengwang.iot.middleware;

// 监听本机11030端口
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.io.InputStream;
import java.io.IOException;
import javax.xml.bind.DatatypeConverter;

public class Router300 {
    public void listenPort() {
        final int PORT = 11030;

        try (ServerSocket serverSocket = new ServerSocket(PORT)) {

            System.out.println("================================ ");
            System.out.println("正在监听端口 " + PORT);

            while (true) {
                try (Socket clientSocket = serverSocket.accept()) {
                    System.out.println("接收到新的连接");

                    InputStream input = clientSocket.getInputStream();
                    byte[] buffer = new byte[1024];
                    int bytesRead;

                    while ((bytesRead = input.read(buffer)) != -1) {
                        // 将字节数组转换为十六进制字符串
                        String hexData = DatatypeConverter.printHexBinary(Arrays.copyOf(buffer, bytesRead));
                        System.out.println("接收到的数据包 (十六进制): " + hexData);
                    }
                } catch (IOException e) {
                    System.err.println("处理客户端连接时出错: " + e.getMessage());
                }
            }
        } catch (IOException e) {
            System.err.println("无法监听端口 " + PORT + ": " + e.getMessage());
        }
    }

    // main
    public static void main(String[] args) {
        Router300 router = new Router300();
        router.listenPort();
    }
}
